﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Text;
using GMS.Utils;
//using GMS.Utils.ServiceContext;
//using GMS.Model;
//using GMS.BLL;
using GMS.Web.CommonPage;
using Maticsoft.DBUtility;
using System.Data.Common;

public partial class CommonPage : GMS.Web.CommonPage.BasePage.CommonBase
{
    HtmlProvider MC = new HtmlProvider();
    public ComOperate CDO = new ComOperate();
    //DBAndBizTableConverter BizTab = new DBAndBizTableConverter();

    public string sModuleID = string.Empty;//模块ID
    public DataSet tableDs = new DataSet();
    private bool detaileditable = false;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            #region moduleid
            //sModuleID = Request.QueryString["ModuleID"];
            //if (OP.UserModuleRight.IndexOf(sModuleID) < 0)
            //{
            //    Response.Write("<script>alert('没有该模块权限！');top.location.href='../Login.aspx';</script>");
            //    return;
            //}/*||(sModuleID==null)*/
            #endregion
            if ((tableCode == null))
            {
                Response.Write("<script>alert('缺少必要参数,无法显示数据!');location.href='MFContent.aspx';</script>");
                return;
            }
            //设置访问权限
            SetAccessRight();
            BindData();
        }
        else
        {
            ClientScript.RegisterStartupScript(this.GetType(), "", "FillControl();", true);
            //设置访问权限
            SetAccessRight();
        }

    }
    protected void Page_Init(object sender, EventArgs e)
    {
        //控制清除按钮的显示
        if (ViewState["comSearch"] != null)
        {
            comSearch = (bool)ViewState["comSearch"];
            ClientScript.RegisterStartupScript(this.GetType(), "", "IsHideBtn(" + (comSearch ? 1 : 0) + ");", true);
        }
    }

    private void BindData()
    {       

        ////设置每页记录行数
        int pageSize;
        if (!int.TryParse(SysSettings.GetPageSize(), out pageSize))
            pageSize = 20;
        txtRowinOnePage.Text = pageSize.ToString();       

        //访问数据库：查找指定行的数据，及查询条件（下拉的）
        CDO = new ComOperate(tableCode/*tabDBCode*/);
        DataSet dsSearch = null;
        try
        {
            tableDs = CDO.GetComData(tableCode, this.initWhere, 0, pageSize, null, null/*OP.CitySelected*/);// CDO.
            Session["tabcode"] = tableCode;
            if (tableDs == null)
                return;
            totalRecordNum = int.Parse(tableDs.Tables["num"].Rows[0][0].ToString());

            //设置页面标题
            if(CDO.Table != null)
                lblTabName.Text = CDO.Table.TABNAME;
            //加载查询条件（下拉的）
            CDO.SetSearchRelation(null/*OP.CitySelectRight*/);
            dsSearch = CDO.GetRelationDataSet();
        }
        catch (Exception ex)
        {
            this.Page.RegisterClientScriptBlock("toAlert", "<script>alert('查询数据出错:" + comUse.SafeAlertMsg(ex.Message + ex.StackTrace) + "');</script>");//关闭窗口
            return;
        }

        //加载查询条件
        LoadSearchControl(dsSearch);

        //审核按钮，上报信息显示
        LoadApprovalDetail(tableCode, null, null);

        //分页设置
        InitPageProperty();

        //加载数据列表
        if (tableDs == null || tableDs.Tables.Count == 0)
            return;
        LoadData(tableDs, 0, pageSize);

        //设置ViewState
        SetViewStateData();
    }

    protected void Page_PreRender(object sender, EventArgs e)
    {
        isRestored = false;
    }

    //特别注意：front：表示从查出来的ds.Tables[0]里面的第front行开始，end行结束，而不是数据库里面的第几行开始和结束
    protected void LoadData(DataSet ds, int front, int end)
    {
        if (ds == null || ds.Tables.Count == 0) //条件查询等要调用的LoadData（），必须判读
            return;        

        //共几条
        lblAllRow.Text = totalRecordNum.ToString();
        bool hasGeom = false;

        DataTable dt = ds.Tables[0];
        tab_content.InnerHtml = "";

        //CDO.Init(tableCode);
        CDO.SetListShowColAdnKeyDic();
        Dictionary<string, GMS.Model.TabColumns> tabColumns = CDO.TabListShowedColDict;
        Dictionary<string, string> keys = CDO.TabKeyDict;

        string tKeys = "";//存放table  keys
        StringBuilder tbodyStr = new StringBuilder();//html string

        Dictionary<string, string>.Enumerator de = keys.GetEnumerator();
        //获取主键
        for (; de.MoveNext(); )
        {
            tKeys += de.Current.Key + ",";
        }
        string[] arr = tKeys.TrimEnd(',').Split(',');

        string columnsString = "";

        //表名带"-"需特殊处理
        if (tableCode.ToUpper().IndexOf("-") >= 0)
        {
            //tabDBCode = BizTab.TableCodeBiz2DB(tableCode); 
            //dt = BizTab.TableColDB2Biz(tableCode, dt);
        }

        //查找不到记录显示
        if (dt.Rows.Count == 0)
        {
            tbodyStr.Append(MC.DisplayTitleWithNoOperation(tabColumns, null,false));
            tbodyStr.Append("<tr>");
            tbodyStr.Append("\r\n");
            tbodyStr.Append("<td colspan='" + Convert.ToString(dt.Columns.Count) + "'>查找不到任何记录！</td>");
            tbodyStr.Append("\r\n");
            tbodyStr.Append("</tr>");
            tbodyStr.Append("\r\n");
            tab_content.InnerHtml = tbodyStr.ToString();
            return;
        }

        //表头信息
        tbodyStr.Append(MC.DisplayTitle(tabColumns, null));
        //有记录显示选中删除按钮
        if (dt.Rows.Count > 0)
        {
            //DelButton.Visible = true;//此按钮由用户对页面的权限进行控制
        }

        //设置每列显示字符串最大长度
        int colMaxSize;
        colMaxSize = int.TryParse(SysSettings.GetTDMaxLength(), out colMaxSize) ? colMaxSize : (int)EnumHelper.E_Constant.CONST_MAXCOLLEN;

        //List<GMS.Model.CitySeq> allCity = Application["CityList"] as List<GMS.Model.CitySeq>;
        //Dictionary<string, string> cityDic = new Dictionary<string, string>();
        //foreach (GMS.Model.CitySeq city in allCity)
        //    cityDic.Add(city.cityname, city.citycode);
        if ((",TAB_OVERLINE,TAB_TOWER,TAB_TRANSFORMER,").IndexOf(Session["tabcode"].ToString().ToUpper()) != -1)
        {
            hasGeom = true;
        }
        StringBuilder scripthigelight = new StringBuilder();
        scripthigelight.Append("<script> parent.clearHightLightedVectors();");
        for (int i = front; (i < dt.Rows.Count) && (i < end); i++)
        {
            string dataId = "";
            for (int z = 0; z < arr.Length; z++)
            {
                dataId += arr[z] + "-" + dt.Rows[i][arr[z]].ToString() + ";";
            }
            dataId = dataId.TrimEnd(';');

            tbodyStr.Append("<tr onmouseover='change_tr_backgroundColor_move(this);' onmouseout='change_tr_backgroundColor_out(this);'>");

            //列是否允许删除
            DateTime? createdt = null;
            //string cityName = string.Empty;
            if (dt.Columns.Contains("createdt") && dt.Rows[i]["createdt"].ToString().Length>0)
                createdt = DateTime.Parse(dt.Rows[i]["createdt"].ToString());
            //if (dt.Columns.Contains("CITYCODE"))
            //    cityName = dt.Rows[i]["CITYCODE"].ToString();
            //bool canDelete = HasDeleteAuth(cityDic.ContainsKey(cityName)? cityDic[cityName]:null, createdt, CDO);
            bool canDelete = true;
            //增加高亮显示脚本功能
            if (hasGeom)
            {
                string condition = "";
                string tabcode = Session["tabcode"].ToString().ToUpper();
                if (tabcode.Equals("TAB_OVERLINE"))
                {
                    condition = "OVERLINEID=" + dt.Rows[i]["OVERLINEID"];
                }
                if (tabcode.Equals("TAB_TOWER"))
                {
                    condition = "TOWERID=" + dt.Rows[i]["TOWERID"];
                }
                if (tabcode.Equals("TAB_TRANSFORMER"))
                {
                    condition = "TRANSID=" + dt.Rows[i]["TRANSID"];
                }


                //for (int k = 0; k < dt.Columns.Count; k++)
                //{
                //    if (dt.Rows[i][k] != dt.Rows[i]["WKT"])
                //    {
                //        string str = dt.Columns[k].ColumnName.Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("\'", "\\\'"); 
                //        condition.Append(str);
                //        condition.Append("   ");
                //        string str2 = dt.Rows[i][k].ToString().Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("\'", "\\\'"); 
                //        condition.Append(str2);
                //        condition.Append("   ");
                //    }
                //}
                scripthigelight.Append("parent.showHightLightedVector(\"" + dt.TableName + "\",\"" + condition + "\",\"" + dt.Rows[i]["WKT"].ToString() + "\");");
            }
            //--------------------
            tbodyStr.Append("<td style=\"width:26px; text-align:left\"><input name=\"chk_item\" type=\"checkbox\" value='" + dataId + "' onclick=\"CheckItem(this,'chk_all');\" " + (canDelete ? "":"disabled")+ " /></td>");

            int num = (int.Parse(lblCpi.Text.ToString()) - 1) * int.Parse(txtRowinOnePage.Text.ToString()) + i + 1;
            if (hasGeom && !(dt.Rows[i]["WKT"].ToString().Equals("")) && !dt.Columns.Contains("LONGITUDE") && !dt.Columns.Contains("LATITUDE"))
            {
                  tbodyStr.Append("<td><a href='javascript:parent.zoomTo(\"" + dt.Rows[i]["WKT"].ToString() + "\")' title=\"点击显示线路在地图位置\">" + num + "</a></td>"); //显示序号
            }
            else 
            { 

                   if (dt.Columns.Contains("LONGITUDE") && dt.Columns.Contains("LATITUDE"))
                   {
                       tbodyStr.Append("<td><a href='javascript:parent.centerAt(" + dt.Rows[i]["LONGITUDE"].ToString() + "," + dt.Rows[i]["LATITUDE"].ToString() + ")' title=\"点击显示目标在地图位置\">" + num + "</a></td>"); //显示序号
                   }
                   else
                   {
                       tbodyStr.Append("<td>" + num + "</td>"); //显示序号
                   }
            }
           foreach (string colcode in tabColumns.Keys)
           {
               if (colcode.Equals("WKT") && hasGeom) { continue; }
               string colValue = dt.Rows[i][colcode].ToString();

               //审核状态字段处理
               //if (ApprovalHelper.IsBatchStatusCol(tableCode, colcode))
               //{
               //    colValue = ApprovalHelper.ConvertBatchNo2Name(colValue);
               //}
               //浮点形数据处理
               if (colValue.Length > 0 && tabColumns[colcode].COLTYPE == (int)EnumHelper.E_ColDataType.COL_FLOAT)
               {
                   int? digits = SysSettings.GetListDecimalDigits();
                   if (digits != null)
                   {
                       colValue = System.Math.Round(Convert.ToDouble(colValue), digits.Value).ToString("N" + digits);

                   }
               }

               //bool 类型显示为 是或者否
               if (colValue.Length > 0 && tabColumns[colcode].COLTYPE == (int)EnumHelper.E_ColDataType.COL_BOOL)
               {
                   if (colValue.Equals("0")) //
                       colValue = "否";
                   else //其他所有值都是 “是” ？
                       colValue = "是";                   
               }

               if (!string.IsNullOrEmpty(tabColumns[colcode].SUBTABCODE) && !string.IsNullOrEmpty(tabColumns[colcode].SUBCOLCODE))
               {   //点击进入子表的其他表的页面的功能：
                   string linkValue = colValue;
                   //下面表示通过自增ID（外键）关联的情况下
                   if (tabColumns[colcode].SUBFOREIGNTYPE != null)
                       if (tabColumns[colcode].SUBFOREIGNTYPE == (int)EnumHelper.E_ColSubGet.COL_SUB_BY_ID)
                       {    //arr是主键（多个字段组合的话，是数组来表示,这里假设主键只有一个字段
                            linkValue = dt.Rows[i][arr[0]].ToString();                            
                       }

                   //字符串要加单引号
                   if (int.Parse(tabColumns[colcode].COLTYPE.ToString()) == (int)EnumHelper.E_ColDataType.COL_STRING)
                       //tbodyStr.Append("<td title='" + Server.HtmlEncode(colValue) + "'><span style=\" text-align:center; cursor:pointer; \" onmousemove=\"change_Style_Mouse_Move(this);\" onmouseout=\"change_Style_Mouse_Out(this);\" onclick='LinkComOtherTable(" + '"' + tabColumns[colcode].SUBTABCODE + "&initWhere=" + tabColumns[colcode].SUBCOLCODE + " in(ψ" + colValue + "ψ)" + "\");'>" + Trucate(colValue, colMaxSize) + "</span></td>");
                       tbodyStr.Append("<td title='" + Server.HtmlEncode(colValue) + "'><a href='javascript:LinkComOtherTable(\"" + tabColumns[colcode].SUBTABCODE + "&initWhere=" + tabColumns[colcode].SUBCOLCODE + " in(ψ" + linkValue + "ψ)" + "\");'>" + Trucate(colValue, colMaxSize) + "</a></td>");
                   else //不加单引号
                       tbodyStr.Append("<td title='" + Server.HtmlEncode(colValue) + "'><span style=\" text-align:center; cursor:pointer; \" onmousemove=\"change_Style_Mouse_Move(this);\" onmouseout=\"change_Style_Mouse_Out(this);\" onclick='LinkComOtherTable(" + '"' + tabColumns[colcode].SUBTABCODE + "&initWhere=" + tabColumns[colcode].SUBCOLCODE + " in(" + colValue + ")" + "\");'>" + Trucate(linkValue, colMaxSize) + "</span></td>");
               }
               else //正常数据，没有链接
                   //tbodyStr.Append("<td title='" + Server.HtmlEncode(colValue) + "'><span style=\" text-align:center; '>" + Trucate(colValue, colMaxSize) + "</span></td>");
                   tbodyStr.Append("<td title='" + Server.HtmlEncode(colValue) + "'><span style=\" text-align:center; \">" + Trucate(colValue, colMaxSize) + "</span></td>");

               //下行代码要留着，是老版本的：点击进入详情页面的功能：
               //tbodyStr.Append("<td title='" + Server.HtmlEncode(colValue) + "'><span style=\" text-align:center; cursor:pointer; \" onmousemove=\"change_Style_Mouse_Move(this);\" onmouseout=\"change_Style_Mouse_Out(this);\" onclick='LinkCom(" + '"' + tableCode + "&cdtion=" + dataId + '"' + ");'>" + Trucate(colValue, colMaxSize) + "</span></td>");
           }
            //详情列
           if (detaileditable)
           {
               tbodyStr.Append("<td title='详情'><span style=\" text-align:center; cursor:pointer; \" onmousemove=\"change_Style_Mouse_Move(this);\" onmouseout=\"change_Style_Mouse_Out(this);\" onclick='LinkCom(" + '"' + tableCode + "&cdtion=" + dataId + "&editable=editable" + '"' + ");'>" + Trucate("详情...", colMaxSize) + "</span></td>");
           }
           else
           {
               tbodyStr.Append("<td title='详情'><span style=\" text-align:center; cursor:pointer; \" onmousemove=\"change_Style_Mouse_Move(this);\" onmouseout=\"change_Style_Mouse_Out(this);\" onclick='LinkCom(" + '"' + tableCode + "&cdtion=" + dataId + "&editable=uneditable" +'"' + ");'>" + Trucate("详情...", colMaxSize) + "</span></td>");
           }
            tbodyStr.Append("</tr>");
        }
        tab_content.InnerHtml = tbodyStr.ToString();
        scripthigelight.Append("</script>");
        this.Page.RegisterStartupScript("myscript",scripthigelight.ToString());
    }

    protected bool HasDeleteAuth(string citycode,DateTime? createDT,ComOperate CDO)
    {
        //if (citycode != null && citycode.Length > 0)
        //{
        //    if (!OP.CityDeleteRight.Contains("'" + citycode + "'"))
        //        return false;
        //}
        if (CDO.Table.NOUPDATEDATE != null && createDT!= null)
            if (CDO.Table.NOUPDATEDATE > createDT)
                return false;
        return true;
    }

    /// <summary>
    /// 加载查询控件
    /// </summary>
    /// <param name="dsData"></param>
    public void LoadSearchControl(DataSet dsData)
    {
        tbQueryCls.InnerHtml = "";
        int iType = 0, iColNum = 0, iDisNum = 4;
        string SelId = string.Empty;
        string SelName = string.Empty;
        string strValue = string.Empty;
        DataTable dtTables = new DataTable();
        Dictionary<string, GMS.Model.TabColumns> relation = new Dictionary<string, GMS.Model.TabColumns>();

        CDO.SetTabColDicAndKeyDic(tableCode);
        Dictionary<string, GMS.Model.TabColumns> tabColumns = CDO.TabColDict;

        StringBuilder qryHTML = new StringBuilder();

        qryHTML.Append("<tr>");
        txtQueryCls.Text = "";
        DataSet relateDS;

        foreach (GMS.Model.TabColumns tabCol in tabColumns.Values)
        {
            if (tabCol.COLSEARCH == (int)GMS.Utils.EnumHelper.E_YesOrNo.No)
                continue;

            if (iColNum % iDisNum == 0)
                qryHTML.Append("</tr>\r\n<tr>");//换行
            iColNum++;
            iType = tabCol.COLTYPE;

            relateDS = new DataSet();
            string value = "";
            string popInfo = "";
            if (!string.IsNullOrEmpty(tabCol.FOREIGNTAB))//表示关联的
            {                
                if (ConstantHelper.IsForeignDropdown(tabCol.FOREIGNTAB.ToUpper()))
                {
                    //下拉框的
                    iType = (int)GMS.Utils.EnumHelper.E_ColDataType.COL_DDL;
                    DataTable tempDT;
                    if (dsData.Tables.Contains(tabCol.COLCODE.ToUpper()))
                    {
                        tempDT = dsData.Tables[tabCol.COLCODE.ToUpper()].Copy();
                        relateDS.Tables.Add(tempDT);
                    }
                    //if (tabCol.FOREIGNTAB.Equals("TAB_CITY") && OP.CitySelected != "")
                    //    value = OP.CitySelected.Trim('\'');


                    foreach (DataTable dt in dsData.Tables)
                    {
                        //当行列是当前表某列的父列
                        if (dt.TableName.ToUpper().StartsWith(tabCol.COLCODE.ToUpper() + "-"))
                        {
                            dtTables = dt;
                            tempDT = dt.Copy();
                            relateDS.Tables.Add(tempDT);
                            iType = (int)GMS.Utils.EnumHelper.E_ColDataType.COL_FDDL;
                            continue;
                        }
                        if (dt.TableName.ToUpper().Contains("-" + tabCol.COLCODE.ToUpper() + "-"))  //父级获得所有父级子级数据
                        {
                            dtTables = null;
                            iType = (int)GMS.Utils.EnumHelper.E_ColDataType.COL_FDDL;
                            break;
                        }
                    }                   
                }
                else//弹出网页选择
                {
                    iType = (int)GMS.Utils.EnumHelper.E_ColDataType.COL_POPSELECT;
                    popInfo = tabCol.FOREIGNCOL + "|" + tabCol.FOREIGNSHOWCOL + "|" + tabCol.COLNAME
                       + "|" + tabCol.FOREIGNTAB + "|Cls-" + tabCol.COLCODE + "-" + iType.ToString();

                    if (tabCol.FOREIGNTAB.ToUpper().Equals("V_TOWER_WIRE"))//潘益民在此填入导线关联的杆塔表（原TAB_HOTEL）的大写
                        popInfo = popInfo + "|BelongLine|所属线路|OverLineID|LineName|Tab_OverLine";//潘益民在此填入导线关联的杆塔字段和as的（原来price as 价格）
                }

                SelId = tabCol.FOREIGNCOL;
                SelName = tabCol.FOREIGNSHOWCOL;
            }

            try
            {
                //display sysArr
                qryHTML.Append(MC.GetSysObjScripts(relateDS,tabCol.FOREIGNTAB));
                //DisplayQuerys
                //注意：下面popInfo的地方原来值是""，也就是说下面调用的时候没有用到这个值，现在用来传递弹出页面的字段相关信息
                qryHTML.Append(MC.DisplayQuerys(iType, false, tabCol.COLCODE, tabCol.COLNAME, value, relateDS, popInfo, SelId, SelName));
            }
            catch (Exception ex)
            {
                this.Page.RegisterClientScriptBlock("toAlert", "<script>alert('查询控件加载出错:" + comUse.SafeAlertMsg(ex.Message + ex.StackTrace) + "');</script>");//关闭窗口
            }

            if (iType == (int)EnumHelper.E_ColDataType.COL_DATE || iType == (int)EnumHelper.E_ColDataType.COL_TIME)
            {
                //下面2行代码需要有，因为当第4个正好是日期类型的时候，会加一个日期（开始日期，结束日期），这样的会使得
                //错过换行（此处iColNum++，上面还有一个iColNum++）
                //if (iColNum % iDisNum == 0)
                //    qryHTML.Append("</tr>\r\n<tr>");//换行
                iColNum++;
                txtQueryCls.Text += "S_Cls-" + tabCol.COLCODE + "-" + iType.ToString() + ";";
                txtQueryCls.Text += "E_Cls-" + tabCol.COLCODE + "-" + iType.ToString() + ";";
            }
            else
                txtQueryCls.Text += "Cls-" + tabCol.COLCODE + "-" + iType.ToString() + ";";
        }
        if (iColNum == 0)
        {
            this.btnQueryNormal.Visible = false;
            this.btnQueryCustom.Visible = false;
        }
        qryHTML.Append("</tr>");
        tbQueryCls.InnerHtml = qryHTML.ToString();
    }

    protected void btnQuery_ServerClick(object sender, EventArgs e)
    {
        string sQuery = string.Empty;
        try
        {
            Dictionary<string, string> values = new Dictionary<string, string>();
            int end = int.Parse(txtRowinOnePage.Text);
            lblCpi.Text = "1";
            GetViewStateData();
            values = GetSearchCondition("",txtQueryCls.Text);
            txtQueryData.Value = queryColData;

            string sqlWhere = string.Empty;
            if ((values != null) && values.Count > 0)
            {
                CDO.GetConditionStr(ref sqlWhere, values, tableCode);
            }
            AddInitConditions(ref sqlWhere);

            DataSet tableDs = CDO.GetComData(tableCode, sqlWhere, 0, end, null, /*OP.CitySelectRight*/null);
            if (tableDs == null)
                return;

            totalRecordNum = int.Parse(tableDs.Tables[1].Rows[0][0].ToString());
            ViewState["totalRecordNum"] = totalRecordNum;
            InitPageProperty();
            LoadData(tableDs, 0, end + 1); //从查出来的dt里面的第1行开始。   
            LoadApprovalDetail(tableCode, values, null);
        }
        catch (Exception ex)
        {
            this.Page.RegisterClientScriptBlock("toAlert", "<script>alert('查询数据读取出错:" + comUse.SafeAlertMsg(ex.Message + ex.StackTrace) + "');</script>");//关闭窗口
        }
    }

    //查询
    protected void SearchData(int start, int end)
    {
        GetViewStateData();
        Dictionary<string, string> values = null;
        DataSet tableDs = null;
        string sqlwhere = string.Empty;
        try
        {
            if (comSearch)
            {
                values = GetSearchCondition(Txt_mysql.Value, txtQueryCls.Text);
                if (values != null && values.Count > 0)
                {
                    CDO.GetConditionStr(ref sqlwhere, values, tableCode);
                }
                txtQueryData.Value = queryColData;
            }
            else
            {
                sqlwhere = hidCustomWhere.Value;
            }
            AddInitConditions(ref sqlwhere);
            tableDs = CDO.GetComData(tableCode, sqlwhere, start, end, null,/*OP.CitySelectRight*/null);// CDO.
            if (tableDs == null)
                return;

            totalRecordNum = int.Parse(tableDs.Tables[1].Rows[0][0].ToString());
            ViewState["totalRecordNum"] = totalRecordNum;
            lblallPage.Text = (totalRecordNum / (int.Parse(txtRowinOnePage.Text.ToString()) + 1) + 1).ToString();//页的总数量
            LoadData(tableDs, 0, end - start + 1); //从查出来的dt里面的第1行开始。
            if (comSearch)
            {
                LoadApprovalDetail(tableCode, values, null);
            }
            else
            {
                LoadApprovalDetail(tableCode, null, hidCustomWhere.Value);
            }
        }
        catch (Exception ex)
        {
            this.Page.RegisterClientScriptBlock("toAlert", "<script>alert('查找出现异常错误:" + comUse.SafeAlertMsg(ex.Message + ex.StackTrace) + "');</script>");//关闭窗口
        }
    }

    //调用查询
    protected void SearchButtonClick(object sender, EventArgs e)
    {
        GetViewStateData();
        int pageSize = int.Parse(txtRowinOnePage.Text);
        lblCpi.Text = "1";
        SearchData(0, pageSize); //点击查询的时候，都是从第一页开始显示的
    }

    //删除数据
    protected void DelButtonClick(object sender, EventArgs e)
    {
        if (isRestored)
            return;
        GetViewStateData();
        Dictionary<string, string> values = new Dictionary<string, string>();//<value,id>
        string delValues = Request.Form["chk_item"];
        if (string.IsNullOrEmpty(delValues))
            return;
        delValues = delValues.Trim();
        string[] delValueArr = delValues.Split(',');

        for (int i = 0; i < delValueArr.Length; i++)
        {
            string[] arr = delValueArr[i].Split(';');
            for (int j = 0; j < arr.Length; j++)
            {
                string[] arr2 = arr[j].Split('-');
                values.Add(arr2[1], arr2[0]);
            }
        }
        int num = 0;
        try{
              num = CDO.ComDelete(tableCode, tableCode, values, /*OP.CitySelectRight*/null);
        }
        catch (Exception ex)
        {
            this.Page.RegisterClientScriptBlock("toAlert", "<script>alert('删除数据出错:" + comUse.SafeAlertMsg(ex.Message + ex.StackTrace) + "');</script>");//关闭窗口
            return;
        }
        if (num != 0)
        {
            int pageSize = int.Parse(txtRowinOnePage.Text);
            DataSet ds;
            string sqlwhere = string.Empty;
            if (comSearch)
            {
                values.Clear();
                values = GetSearchCondition("", txtQueryCls.Text);
                txtQueryData.Value = queryColData;

                if (values.Count > 0)
                {
                    CDO.GetConditionStr(ref sqlwhere, values, tableCode);
                }
            }
            else
            {
                sqlwhere = hidCustomWhere.Value;
            }
            AddInitConditions(ref sqlwhere);

            ds = CDO.GetComData(tableCode, sqlwhere, 0, pageSize, null, /*OP.CitySelectRight*/null);
            totalRecordNum = int.Parse(ds.Tables[1].Rows[0][0].ToString());
            ViewState["totalRecordNum"] = totalRecordNum;
            this.lblCpi.Text = "1";
            InitPageProperty();
            LoadData(ds, 0, int.Parse(txtRowinOnePage.Text));
            LoadApprovalDetail(tableCode, null, null);
            
            Alert("删除成功！");
        }
        else
        {
            Alert("删除出现异常，请联系管理员！");
        }
    }

    //点击列进行排序
    protected void SortButtonClick(object sender, EventArgs e)
    {
        try
        {
            GetViewStateData();
            string str = SortTxt.Value;
            int curPage = int.Parse(lblCpi.Text.ToString());
            int pageSize = int.Parse(txtRowinOnePage.Text);
            int start = (curPage - 1) * pageSize;
            int end = curPage * pageSize;
            Dictionary<string, string> values = GetSearchCondition(Txt_mysql.Value, txtQueryCls.Text);
            txtQueryData.Value = queryColData;

            CDO.SetTabColDicAndKeyDic(tableCode);
            Dictionary<string, GMS.Model.TabColumns> tabColDict = CDO.TabColDict;
            if (tabColDict == null || tabColDict.Count == 0)
                return;
            string sortStr = null;
            foreach (KeyValuePair<string, GMS.Model.TabColumns> kvp in tabColDict)
            {
                if (str.Equals(kvp.Value.COLNAME))
                {

                    if (sortAsc == true)
                    {
                        sortAsc = false;
                        sortStr = " order by a." + kvp.Value.COLCODE + " DESC";
                    }
                    else
                    {
                        sortAsc = true;
                        sortStr = " order by a." + kvp.Value.COLCODE + " ASC";
                    }

                    ViewState["sortAsc"] = sortAsc; //更新sortAsc(值已经改变）
                    break;
                }

            }
            DataSet tableDs;

            string sqlwhere = string.Empty;
            if (comSearch && values.Count>0)
            {

                CDO.GetConditionStr(ref sqlwhere, values);
            }
            else
            {
                sqlwhere = hidCustomWhere.Value;
            }
            AddInitConditions(ref sqlwhere);
            tableDs = CDO.GetComData(tableCode, sqlwhere, start, end, sortStr, /*OP.CitySelectRight*/null);
            LoadApprovalDetail(tableCode, null, sqlwhere);
            LoadData(tableDs, 0, tableDs.Tables[0].Rows.Count);
        }
        catch (Exception ex)
        {
            this.Page.RegisterClientScriptBlock("toAlert", "<script>alert('排序出现异常错误:" + comUse.SafeAlertMsg(ex.Message + ex.StackTrace) + "');</script>");//关闭窗口
        }
    }

    #region 导出
    protected void Btn_Export(object sender, EventArgs e)
    {
        GetViewStateData();
        int i = 0;
        DataSet ds;
        string sqlwhere = string.Empty;
        Dictionary<string, string> values = new Dictionary<string, string>();

        string delValues = Request.Form["chk_item"];
        if (string.IsNullOrEmpty(delValues))
        {
            //导出普通查询与自定义查询过滤后的数据
            comSearch = (bool)ViewState["comSearch"];

            if (comSearch)
            {
                values = GetSearchCondition(Txt_mysql.Value, txtQueryCls.Text);
                if (values.Count > 0)
                {
                    CDO.GetConditionStr(ref sqlwhere, values, tableCode);
                }
                txtQueryData.Value = queryColData;
            }
            else
            {
                sqlwhere = hidCustomWhere.Value;
            }
        }
        else
        {
            //导出已勾选的记录
            string[] delValueArr = delValues.Trim().Split(',');

            for (int k = 0; k < delValueArr.Length; k++)
            {
                string[] arr = delValueArr[k].Split(';');
                for (int j = 0; j < arr.Length; j++)
                {
                    string[] arr2 = arr[j].Split('-');
                    values.Add(arr2[1], arr2[0]);
                }
            }
            if (values.Count > 0)
            {
                sqlwhere = CDO.GetCheckDelSqlWhere(values, tableCode);
            }
        }
        AddInitConditions(ref sqlwhere);
        ds = CDO.GetComData(tableCode, sqlwhere, 0, 0, null, /*OP.CitySelectRight*/null);
        if (ds == null)
        {
            Alert("没有可导出数据！");
            return;
        }
        //设置导出文件名
        string fileName = lblTabName.Text + DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls";
        ExportToFile(ds, 1, Server.UrlEncode(fileName));
    }

    public void ExportToFile(DataSet ds, int typeId, string fileName)
    {
        HttpResponse resp;
        resp = Page.Response;
        resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        resp.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);

        // typeid==1时导出为EXCEL格式文件；typeid==2时导出为XML格式文件 
        if (typeId == 1)
        {
            //显示中文名的列标题：
            DataTable dt = ds.Tables[0];
            CDO.SetExportCol(tableCode);
            dt.TableName = lblTabName.Text;//用中文表名代替英文表名显示在excel的标题上
            GMS.Web.CommonPage.TableUtility.ToExcelBook(CDO.TabExportColDict, dt).Save(resp.OutputStream);
        }
        else if (typeId == 2)
        {
            //从DataSet中直接导出XML数据并且写到HTTP输出流中 
            resp.Write(ds.GetXml());
        }
        //写缓冲区中的数据到HTTP头文件中 
        resp.End();
    }
    #endregion

    public void BtnNewClick(object sender, EventArgs e)
    {
        string url = string.Empty;
        GetViewStateData();
        if (tableCode.ToUpper().IndexOf("TAB_GATHERHOTSCHEME") >= 0 && !tableCode.ToUpper().Equals("TAB_GATHERHOTSCHEME"))
        {
            url = "../DMWEB/WLAN/GatherHotsemes_Details.aspx?tablecode=" + tableCode;
        }
        else if (tableCode.ToUpper().IndexOf("TAB_CoverTopicGather-".ToUpper()) >= 0)
        {
            tableCode = "TAB_CoverTopic-" + tableCode.Substring(tableCode.IndexOf('-') + 1, tableCode.Length - tableCode.IndexOf('-') - 1);
            url = "../DMWEB/WLAN/GatherTopic.aspx?tablecode=" + tableCode;
        }
        else if (tableCode.ToUpper().IndexOf("TAB_CoverTopicTotal".ToUpper()) >= 0)
        {
            url = "../DMWEB/WLAN/GatherTopicTotal.aspx";
        }
        else if (tableCode.ToUpper().Equals("TAB_HOTPOINTSTAT"))
        {
            url = "../DMWEB/HotPointStat/HosPointStat.aspx?tablecode=" + tableCode;
        }
        else
        {
            url = "CommonPageDetails.aspx?tablecode=" + tableCode;
        }
        this.Page.Response.Redirect(url);

    }

    #region 翻页设置
    private void InitPageProperty()
    {
        this.JumpPage.Text = this.lblCpi.Text;
        this.JumpPage.Enabled = totalRecordNum <= 1 ? false : true;
        if (totalRecordNum <= int.Parse(txtRowinOnePage.Text.ToString()))
        {
            LbtNextPage.Enabled = false;
            LbtLastPage.Enabled = false;
        }
        else
        {
            LbtNextPage.Enabled = true;
            LbtLastPage.Enabled = true;
        }
        int pagsize = int.Parse(txtRowinOnePage.Text.ToString());
        lblallPage.Text = totalRecordNum == 0 ? "1" :(totalRecordNum % pagsize == 0 ? totalRecordNum / pagsize : totalRecordNum / pagsize + 1).ToString();//(totalRecordNum / (int.Parse(txtRowinOnePage.Text.ToString()) + 1) + 1).ToString();//页的总数量
        LbtFirstPage.Enabled = false;
        LbtPreviousPage.Enabled = false;
    }

    /// <summary>
    /// 首页按钮
    /// </summary>
    protected void FirstPageClick(object sender, EventArgs e)
    {
        lblCpi.Text = "1";
        DBbind(lblCpi.Text);
        this.JumpPage.Text = this.lblCpi.Text;

    }
    /// <summary>
    /// 上一页
    /// </summary>
    protected void PreviousPageClick(object sender, EventArgs e)
    {
        if (int.Parse(lblCpi.Text) > 1)
        {
            lblCpi.Text = (int.Parse(lblCpi.Text) - 1).ToString();
            DBbind(lblCpi.Text);
            this.JumpPage.Text = this.lblCpi.Text;
        }
    }
    /// <summary>
    /// 下一页
    /// </summary>
    protected void NextPageClick(object sender, EventArgs e)
    {
        if (int.Parse(lblCpi.Text) < int.Parse(lblallPage.Text))
        {
            lblCpi.Text = (int.Parse(lblCpi.Text) + 1).ToString();
            DBbind(lblCpi.Text);
            this.JumpPage.Text = this.lblCpi.Text;
        }
    }
    /// <summary>
    /// 尾页
    /// </summary>
    protected void LastPageClick(object sender, EventArgs e)
    {
        lblCpi.Text = lblallPage.Text.Equals("0") ? "1" : lblallPage.Text;
        DBbind(lblCpi.Text);
        this.JumpPage.Text = this.lblCpi.Text;

        this.LbtFirstPage.Enabled = true;
        this.LbtLastPage.Enabled = false;
    }
    /// <summary>
    /// 绑定数据
    /// </summary>
    public void DBbind(string curNum)
    {
        GetViewStateData();
        if (curNum.Equals("0"))
            curNum = "1";

        LbtFirstPage.Enabled = true;
        LbtLastPage.Enabled = true;
        LbtPreviousPage.Enabled = true;
        LbtNextPage.Enabled = true;

        int curPage = int.Parse(curNum);
        int pageSize = int.Parse(txtRowinOnePage.Text);
        int start = (curPage - 1) * pageSize;
        int end = curPage * pageSize;
        SearchData(start, end);


        //算出总的页数
        if (totalRecordNum % pageSize != 0)
        {
            lblallPage.Text = (totalRecordNum / pageSize + 1).ToString();//页的总数量
        }
        else
        {
            lblallPage.Text = (totalRecordNum / pageSize).ToString();
        }  

        if (this.lblallPage.Text.ToString().Equals("0"))//0页
        {
            this.lblCpi.Text = "0";
            this.LbtNextPage.Enabled = false;
            this.LbtLastPage.Enabled = false;
            this.JumpPage.Enabled = false;
        }
        else if (this.lblallPage.Text.ToString().Equals("1"))//1页
        {
            this.LbtNextPage.Enabled = false;
            this.LbtLastPage.Enabled = false;
            this.JumpPage.Enabled = false;
        }
        else //多页
        {
            this.LbtNextPage.Enabled = true;
            this.LbtLastPage.Enabled = true;
            this.JumpPage.Enabled = true;

        }
        //判断是首页 
        if (curNum.Equals("1"))
        {
            this.LbtFirstPage.Enabled = false;
            this.LbtPreviousPage.Enabled = false;
        }
        //判断是尾页
        if (lblallPage.Text.ToString().Equals(curNum))
        {
            this.LbtNextPage.Enabled = false;
            this.LbtLastPage.Enabled = false;
        }

        //AllGv.DataSourceID = DS.Text;
        if (!lblAllRow.Text.Equals("0") && curNum.Equals("1"))
        {
            this.lblCpi.Text = "1";
        }
    }
    protected void txtRowinOnePage_TextChanged(object sender, EventArgs e)
    {
        check_txtRowinOnePage();
        DBbind(this.lblCpi.Text);
    }
    public void check_txtRowinOnePage()//检查输入每页的行数
    {
        if (txtRowinOnePage.Text.Trim().Equals("") || !comUse.IsNumber(txtRowinOnePage.Text.Trim()))
        {
            txtRowinOnePage.Text = SysSettings.GetSysSetting("每页记录数");
            this.Page.RegisterClientScriptBlock("toAlert", "<script>alert('请输入正整数！系统默认是每页 " + txtRowinOnePage.Text + " 条');</script>");
            return;
        }
        if (int.Parse(txtRowinOnePage.Text) < 1)
        {
            txtRowinOnePage.Text = SysSettings.GetSysSetting("每页记录数");
            this.Page.RegisterClientScriptBlock("toAlert", "<script>alert('请输入正整数！系统默认是每页 " + txtRowinOnePage.Text + " 条');</script>");
        }
    }
    protected void JumpPageTextChanged(object sender, EventArgs e)//第几页
    {
        if (this.JumpPage.Text == null || !comUse.IsNumber(this.JumpPage.Text))
        {
            this.Page.RegisterClientScriptBlock("toAlert", "<script>alert('请输入正整数！');history.back(-1);</script>");
            return;
            //this.Page.Response.Redirect(GetReturnUrl());          
        }

        if (int.Parse(this.JumpPage.Text) > 0 && int.Parse(this.JumpPage.Text) <= int.Parse(this.lblallPage.Text))
        {
            this.lblCpi.Text = this.JumpPage.Text;
            DBbind(this.JumpPage.Text);
        }
        else
        {
            this.Page.RegisterStartupScript("", "<script>alert('超过页数范围，请重新输入！');history.back(-1);</script>");
            //不能直接调用下面的语句（有redirect），那么前面的alert就出不来
            //ReturnBack();
        }
    }
    #endregion

    //自定义查询
    protected void BtnCustomSearch_Click(object sender, EventArgs e)
    {
        if (!isRestored)
        {
            comSearch = (bool)ViewState["comSearch"];
            if (comSearch)
                comSearch = false;
            else
                comSearch = true;
            ViewState["comSearch"] = comSearch;
            txtQueryData.Value = "";
            bool bShowDataWhenClickCustSearch = true;
            if (comSearch)//关闭自定义查询
            {
                tbCustom.Visible = false;
                tbQueryCls.Visible = true;
                btnQueryNormal.Visible = true;
                btnQueryCustom.Visible = false;
                BtnCustomSearch.Text = "复杂查询";
                BtnClear_S.Visible = true;
                BtnClear_CS.Visible = false;
                tab_content.EnableViewState = false;
                btnQuery_ServerClick(null, null);
                BtnClear_Click(null, null);
            }
            else//开启自定义查询
            {
                LisColData();
                tbCustom.Visible = true;
                tbQueryCls.Visible = false;
                btnQueryNormal.Visible = false;
                btnQueryCustom.Visible = true;
                BtnCustomSearch.Text = "简单查询";
                tab_content.EnableViewState = true;
                BtnClear_CS.Visible = true;
                BtnClear_S.Visible = false;

                //点击自定义查询的时候是否直接显示一些数据
                if (bShowDataWhenClickCustSearch)
                {
                    btnQuery_ServerClick(null, null);
                    BtnClear_Click(null, null);
                }
                else
                {
                    lblallPage.Text = "0";
                    lblAllRow.Text = "0";
                    lblCpi.Text = "1";
                    LbtFirstPage.Enabled = false;
                    LbtLastPage.Enabled = false;
                    LbtNextPage.Enabled = false;
                    LbtPreviousPage.Enabled = false;
                }
            }
        }
    }

    //审核相关显示
    private void LoadApprovalDetail(string tab, Dictionary<string, string> value, string sqlWhere)
    {
        //GMS.BLL.TabInfoBLL tabInfoBLL = new GMS.BLL.TabInfoBLL();
        //bool tabIsApp = tabInfoBLL.IsApproval(tab);

        ////如果是审核表，显示查看审核结果按钮
        //if (tabIsApp)
        //{
        //    this.BtnQueryApp.Visible = true;
        //}
        //else
        //{
        //    this.BtnQueryApp.Visible = false;
        //}

        //this.ApprovalDataDiv.InnerHtml = string.Empty;
        ////如果有数据需要审核显示审核按钮
        //if (isApprovalData(tab))
        //{
        //    this.BtnApproval.Visible = true;
        //    this.BtnUrgent.Visible = true;
        //    this.BtnUrgentLinkMan.Visible = true;
        //}
        //else
        //{
        //    this.BtnApproval.Visible = false;
        //    this.BtnUrgent.Visible = false;
        //    this.BtnUrgentLinkMan.Visible = false;
        //}

        ////显示已上报分公司和未上报分公司
        //tab = BizTab.TableCodeBiz2DB(tab);
        //List<string> citys = CDO.GetCityHasSubmited(tab.ToUpper(), value, sqlWhere, OP.CitySelectRight);
        //if (citys == null)
        //{
        //    return;
        //}
        //ApprovalDataDiv.Visible = true;
        //List<GMS.Model.CitySeq> allCity = Application["CityList"] as List<GMS.Model.CitySeq>;
        //int hasSubmit=0;
        //int notSubmit = 0;
        //string hasApprovalCity = string.Empty;
        //string hasNotApprovalCity = string.Empty;
        //foreach (GMS.Model.CitySeq city in allCity)
        //{
        //    if (OP.CitySelectRight.Contains("" + city.citycode + "'"))
        //    {
        //        if (citys.Contains(city.cityname))
        //        {
        //            hasApprovalCity += city.cityname + "，";
        //            hasSubmit++;
        //        }
        //        else
        //        {
        //            hasNotApprovalCity += city.cityname + "，";
        //            notSubmit++;
        //        }
        //    }

        //}
        //this.ApprovalDataDiv.InnerHtml = "已上报分公司（" + hasSubmit + "个）：" + hasApprovalCity.TrimEnd('，');
        //this.ApprovalDataDiv.InnerHtml += "<br />";
        //this.ApprovalDataDiv.InnerHtml += "未上报分公司（" + notSubmit + "个）：" + hasNotApprovalCity.TrimEnd('，');
    }

    protected void BtnApproval_Click(object sender, EventArgs e)
    {
        tableCode = (string)ViewState["tableCode"];
        string url = "../DMWEB/Approval/Approval.aspx?table=" + tableCode + "&check=c";
        //this.Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>JumpToPage('" + url + "');</script>");
        this.Page.Response.Redirect(url);
    }
    protected void BtnRemark_Click(object sender, EventArgs e)
    {
        tableCode = (string)ViewState["tableCode"];
        string url = "~/Public/TabRemark.aspx?table=" + tableCode;
        this.Page.Response.Redirect(url);
    }
    protected void BtnImportClick(object sender, EventArgs e)
    {
        tableCode = (string)ViewState["tableCode"];
        string url = "~/Public/ExcelImport/ExcelDbImport.aspx?TableName=" + tableCode;
        //this.Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>JumpToPage('" + url + "');</script>");
        this.Page.Response.Redirect(url);
    }

    /// <summary>
    /// 加载自定义查询信息
    /// </summary>
    private void LisColData()
    {
        if (tableCode == null || tableCode.Equals(""))
            tableCode = (string)ViewState["tableCode"];

        DataTable dt = null;
        if ((int)EnumHelper.E_DbType.DB_ACCESS == PubConstant.GetDBType())
        {
            GMS.BLL.TabColumnsAccessBLL bll = new GMS.BLL.TabColumnsAccessBLL();
            dt = bll.GetColListAllowedOrderSEQ(tableCode);
        }
        else if ((int)EnumHelper.E_DbType.DB_SQL == PubConstant.GetDBType())
        {
            GMS.BLL.TabColumnsBLL bll = new GMS.BLL.TabColumnsBLL();
            dt = bll.GetColListAllowedOrderSEQ(tableCode);
        }
        else if ((int)EnumHelper.E_DbType.DB_ORACLE == PubConstant.GetDBType())
        {
            GMS.BLL.TabColumnsOraBLL bll = new GMS.BLL.TabColumnsOraBLL();
            dt = bll.GetColListAllowedOrderSEQ(tableCode);
        }
        else
            return;
        

        if (dt != null)
        {
            lbCustomColCode.DataTextField = "COLNAME";
            lbCustomColCode.DataValueField = "COLCODE";

            //此处把列名都加上:-数据类型，主要用于点击列表框，用js根据数据类型自动过滤一些操作
            foreach (DataRow row in dt.Rows)
            {
                if(row["FOREIGNTAB"] == null || row["FOREIGNTAB"].ToString().Equals(""))
                    row["COLCODE"] = row["COLCODE"].ToString() + "-" + row["COLTYPE"].ToString();
                else //有外键，数据类型用9来表示
                    row["COLCODE"] = row["COLCODE"].ToString() + "-"+ ((Int16)EnumHelper.E_ColDataType.COL_DDL).ToString();
                    
            }
            lbCustomColCode.DataSource = dt;
            lbCustomColCode.DataBind();

            //Dictionary<string, string> cols = new Dictionary<string, string>();
            //foreach (DataRow row in dt.Rows)
            //{
            //    cols.Add(row["COLCODE"].ToString(), row["COLNAME"].ToString());
            //}
        }
    }

    protected void BtnCustomClear_Click(object sender, EventArgs e)
    {
        tbCustomSel.Text = string.Empty;
        hidCustomWhere.Value = string.Empty;
    }


    protected void BtnCustomAdd_Click(object sender, EventArgs e)
    {
        //lbCustomColCode.Text:字段名（英文）
        //lbCustomOpr.Text：操作符（如>, <, = like等
        //tbCustomSel.Text：保存显示的条件
        //hidCustomWhere.Value：保存真实的查询条件

        string whereValue = TBInptValue.Text.Trim();
        string colcode = lbCustomColCode.Text.ToUpper();
        if(string.IsNullOrEmpty(colcode))
        {
            CommPageAlert("字段名出错，请联系管理员！");
            return;
        }
        string[] arr = colcode.Split('-');
        colcode = arr[0];

        int numForeign = 0;//关联表第几个关联

        if (tableCode == null || tableCode.Equals(""))
            tableCode = (string)ViewState["tableCode"];
        if (lbCustomColCode.Text.Length == 0 || lbCustomOpr.Text.Length==0)
        {
            CommPageAlert("请选择列和条件！");
            return;
        }

        if (whereValue.Length == 0)
        {
            CommPageAlert("值不能为空！");
            return;
        }
        whereValue = StringHelper.SafeSQLString(whereValue);

     
        CDO.SetTabColDicAndKeyDic(tableCode);
        string foreignTab = CDO.TabColDict[colcode].FOREIGNTAB.ToUpper();
        int type = CDO.TabColDict[colcode].COLTYPE;
        string chineseColName = CDO.TabColDict[colcode].COLNAME;
        //模糊匹配
        if (lbCustomOpr.Text=="like") 
        {
            if (type == (int)EnumHelper.E_ColDataType.COL_STRING || foreignTab.Length>0)
                whereValue = "%" + whereValue + "%";
            else
            {
                CommPageAlert(chineseColName + "类型限制，不能进行模糊匹配,请更改条件或列！");
                return;
            }
        }
        //操作符
        if (tbCustomSel.Text.Length > 0 && hidCustomWhere.Value.Length > 0)
        {
            if (Request.Form["radioWhere"] == "and")
            {
                tbCustomSel.Text += "<br/> 并且 ";
                hidCustomWhere.Value += "and ";
            }
            else
            {
                tbCustomSel.Text += "<br/> 或者 ";
                hidCustomWhere.Value += "or  "; //注意，和前面"and "的字符数4个相同，这样后面当多次添加，可以去掉
            }
        }

        string newSel = chineseColName + " " + lbCustomOpr.SelectedItem.Text + " " + whereValue;
        if (tbCustomSel.Text.ToString().IndexOf(newSel) >= 0) //已经包含了这个条件（用户多次点击相同的操作）
        {
            //this.Page.RegisterStartupScript("", "<script>alert('" + newSel + "查询条件已经添加过了，不能多次添加完全相同的条件！');</script>");
            CommPageAlert("\"" + newSel + "\" 查询条件已经添加过了，不能多次添加完全相同的条件！");
            hidCustomWhere.Value = hidCustomWhere.Value.Substring(0, hidCustomWhere.Value.Length - 4); //去掉"or  "或者"and "
            tbCustomSel.Text = tbCustomSel.Text.Substring(0, tbCustomSel.Text.Length - 9);
            return;
        }
        else //还没添加过
            tbCustomSel.Text += newSel;//tbCustomSel是显示出来的条件

        //查询条件
        if (foreignTab.Length == 0)
        {
            if (type == (int)EnumHelper.E_ColDataType.COL_AUTOID
                || type == (int)EnumHelper.E_ColDataType.COL_INT || type == (int)EnumHelper.E_ColDataType.COL_FLOAT)
            {
                hidCustomWhere.Value += "a." + colcode + " " + lbCustomOpr.Text + " " + whereValue + "  ";
            }
            else if (type == (int)EnumHelper.E_ColDataType.COL_TIME || type == (int)EnumHelper.E_ColDataType.COL_DATE)
            {                //时分秒？            
                hidCustomWhere.Value += "to_char(" + "a." + colcode + ",'yyyy-mm-dd')" + lbCustomOpr.Text + "'" + whereValue + "'  ";
            }
            else if(type == (int)EnumHelper.E_ColDataType.COL_BOOL)
            {
                string strBool = "";
                if (whereValue.Equals("是"))
                    strBool = "1";
                else if (whereValue.Equals("否"))
                    strBool = "0";
                else
                {
                    CommPageAlert("必须输入 是 或者 否 ");//不能弹出
                    return;
                }

                hidCustomWhere.Value += "a." + colcode + " " + lbCustomOpr.Text + " " + strBool + "  ";
            }
            else //字符串
            {
                hidCustomWhere.Value += "a." + colcode + " " + lbCustomOpr.Text + " \'" + whereValue + "\'  ";
            }
        }
        else
        {
            foreach (GMS.Model.TabColumns col in CDO.TabColDict.Values)
            {
                if (foreignTab.Equals(col.FOREIGNTAB.ToUpper()))
                    numForeign++;
                if (colcode == col.COLCODE.ToUpper())
                    break;
            }

            if (foreignTab.Equals(ConstantHelper.C_SYSPARA_TABNAME.ToUpper()))
            {
                hidCustomWhere.Value += "B" + numForeign+ "." +CDO.TabColDict[colcode].FOREIGNSHOWCOL + " "
                    + lbCustomOpr.Text + " \'" + whereValue + "\'  ";
            }
            else //其他关联的表不设置别名，直接用表名
            {
                hidCustomWhere.Value += foreignTab + numForeign + "." + CDO.TabColDict[colcode].FOREIGNSHOWCOL + " "
                    + lbCustomOpr.Text + " \'" + whereValue + "\'  ";
            }
        }
    }

    protected void BtnCustomSearchOpr_Click(object sender, EventArgs e)
    {
        GetViewStateData();
        int pageSize = int.Parse(txtRowinOnePage.Text);
        try
        {
            //点击查询的时候，都是从第一页开始显示的      
            CDO.IsCustomSearch = true;
            string sqlwhere = hidCustomWhere.Value;
            AddInitConditions(ref sqlwhere);
            DataSet tableDs = CDO.GetComData(tableCode, sqlwhere, 0, pageSize, null, /*OP.CitySelectRight*/null);
            totalRecordNum = int.Parse(tableDs.Tables[1].Rows[0][0].ToString());
            ViewState["totalRecordNum"] = totalRecordNum;
            InitPageProperty();
            LoadData(tableDs, 0, pageSize + 1); //从查出来的dt里面的第1行开始。
        }
        catch (Exception ex)
        {
            this.Page.RegisterClientScriptBlock("toAlert", "<script>alert('查询出错，请检查查询条件:" + comUse.SafeAlertMsg(ex.Message + ex.StackTrace) + "');</script>");//关闭窗口
        }
    }


    protected void BtnClear_Click(object sender, EventArgs e)
    {
        TBInptValue.Text = string.Empty;
        tbCustomSel.Text = string.Empty;
        hidCustomWhere.Value = string.Empty;
    }
    protected void BtnQueryApp_Click(object sender, EventArgs e)
    {
        tableCode = (string)ViewState["tableCode"];
        string url = "../DMWEB/Approval/Approval.aspx?table=" + tableCode + "&check=q";
        //this.Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>JumpToPage('" + url + "');</script>");
        this.Page.Response.Redirect(url);
    }
    protected void BtnUrgent_Click(object sender, EventArgs e)
    {
        //获得未上报分公司
        //string tabCode = Request.QueryString["table"];
        //tabCode = tabCode.ToUpper();
        //string urgentCityName = "";
        ////List<string> citys = CDO.GetCityHasSubmited(tabCode, null, null,/*OP.CitySelectRight*/null);
        ////if (citys != null)
        ////{
        ////    List<GMS.Model.CitySeq> allCity = Application["CityList"] as List<GMS.Model.CitySeq>;
        ////    foreach (GMS.Model.CitySeq city in allCity)
        ////    {
        ////        if (OP.CitySelectRight.Contains("" + city.citycode + "'"))
        ////        {
        ////            if (!citys.Contains(city.cityname))
        ////            {
        ////                urgentCityName += ",'" + city.cityname + "'";
        ////            }
        ////        }

        ////    }

        ////}
        //if (urgentCityName != "")
        //    urgentCityName = urgentCityName.Substring(1);

        //GMS.BLL.TabInfoBLL tabinfoBll = new GMS.BLL.TabInfoBLL();
        //GMS.Model.TabInfo tabModel = tabinfoBll.GetModel(tabCode);

        //if (tabModel.GROUPID != null && tabModel.GROUPID.ToString() != "" && urgentCityName != null && urgentCityName != "")
        //{
        //    string where = "Exists(Select 1 From tab_group_addrlist Where groupid = '" + tabModel.GROUPID + "' And addrlistid = tab_address_list.Id)"
        //        + " and (select cityname from tab_city where citycode=company) in(" + urgentCityName + ")";
        //    GMS.BLL.AddressListBLL bll = new GMS.BLL.AddressListBLL();
        //    List<GMS.Model.AddressList> models = bll.GetModelList(where);
        //    StringBuilder emailAddr = new StringBuilder();
        //    string defaultEmailType = SysSettings.GetDefaultEmail();
        //    foreach (GMS.Model.AddressList model in models)
        //    {
        //        emailAddr.Append(";\"" + model.NAME + "\"<" + StringHelper.GetDefaultNotNullEmail(defaultEmailType, model.EMAILBYOA, model.EMAILBY189, model.EMAILBYTHIRD) + ">");
        //    }
        //    MailInfoUrgent.SendTo = emailAddr.ToString().Length > 1 ? emailAddr.ToString().Substring(1) : "";
        //}
        //MailInfoUrgent.Subject = SysSettings.GetSysSetting("环评催报通知标题");
        //MailInfoUrgent.Body = SysSettings.GetSysSetting("通知邮件内容");

        //this.Page.RegisterStartupScript("", "<script>showabSoluteDiv();</script>");
    }

    protected void BtnUrgentLinkMan_Click(object sender, EventArgs e)
    {
        string tabCode = Request.QueryString["table"];
        tabCode = tabCode.ToUpper();
        GMS.BLL.TabInfoBLL tabinfoBll = new GMS.BLL.TabInfoBLL();
        GMS.Model.TabInfo tabModel = tabinfoBll.GetModel(tabCode);
        //if (tabModel.GROUPID == null)
        //    RegisterClientScriptBlock("", "<script>alert('该表没有定义催报相关组,请联系管理员添加设定相相关组!');</script>");
        //else
        //    Response.Redirect(Request.ApplicationPath + "/DMWEB/AddressBook/Address/addresslist.aspx?GROUPID=" + tabModel.GROUPID);
    }
    protected void TB_SendEmail_Click(object sender, EventArgs e)
    {
        //EmailTool.SMTPServer smtpServer = new EmailTool.SMTPServer();
        //GMS.Model.MailPlanConfig c = new GMS.DAL.MailPlanConfigDAL().GetModel();
        //smtpServer.Ip = c.SmtpHost;
        //smtpServer.Port = Convert.ToInt32(c.SmtpPort);
        //smtpServer.Account = c.SmtpUser;
        //smtpServer.Password = c.SmtpPassword;
        //smtpServer.RequireAuthorized = bool.Parse(c.SmtpAuth);

        //EmailTool.Mail email = new EmailTool.Mail();
        //email.Sendfrom = System.Configuration.ConfigurationSettings.AppSettings["MailFrom"];    //或此处取登陆人的联系方式中的邮箱
        //email.Subject = MailInfoUrgent.Subject;
        //email.Content = MailInfoUrgent.Body;
        ////string[] address = txbSendTo.Text.Split(',');
        ////for (int i = 0; i < address.Length; i++)
        ////{
        ////    email.Sendto = address[i];
        ////    EmailTool.HandleEmail.SendMail(email, smtpServer);
        ////}
        //email.Sendto = StringHelper.FormatMailString(MailInfoUrgent.SendTo);
        //EmailTool.HandleEmail.SendMail(email, smtpServer);
    }
    protected void lbCustomOpr_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
    protected void Btn_Print(object sender, EventArgs e)
    {
    }

    private void DoRight(GMS.Model.User user, int TabSysID)
    {
        int[] right = RoleModuleRightOper.GetRoleModuleRightInt(user, TabSysID);

        foreach (int i in right)
        {
            switch (i)
            {
                case (int)EnumHelper.E_Right.R_SEARCH:
                    BtnCustomSearch.Visible = true;
                    break;
                case (int)EnumHelper.E_Right.R_INSERT:
                    BtnNew.Visible = true;
                    //BtnImport.Visible = true;
                    break;
                case (int)EnumHelper.E_Right.R_UPDATE:
                    detaileditable = true;
                    break;
                case (int)EnumHelper.E_Right.R_DELETE:
                    DelButton.Visible = true;
                    break;
                default:
                    break;
            }
        }
    }

    private void SetAccessRight()
    {
        GMS.Model.User user = (GMS.Model.User)Session["_User"];
        if (user == null)
        {
            Response.Write("<script>alert('登陆已过期，请重新登陆！');top.location.href='" + Request.ApplicationPath + "/Login.aspx';</script>");
            return;
        }
               
        //int TabSysID = 32;//在没有配置好url前，为保证运行设置
        int TabSysID; //模块ID
        if (Request.Params["TabSysID"] != null)
        {
            TabSysID = Int32.Parse(Request.Params["TabSysID"]);
            if (Session["TabSysID"] == null)
            {
                Session.Add("TabSysID", TabSysID);
            }
            else
            {
                Session["TabSysID"] = TabSysID;
            }

            DoRight(user, TabSysID);            
        }
        else if (Session["TabSysID"] != null)
        {            
            DoRight(user, Int32.Parse(Session["TabSysID"].ToString()));
        }
        else
        {
            SetAllRight();
        }

        //视图不要有删除、插入等，应该从tabinfo表中配置更加合理些
        //string str = CDO.TabColDict["_defaultorder"];
        if (tableCode == null || tableCode.Equals(""))
            tableCode = (string)ViewState["tableCode"];
        if (!string.IsNullOrEmpty(tableCode))
        {
            if (tableCode.IndexOf("V_") == 0)//以“V_”开头 
            {
                BtnNew.Visible = false;
                DelButton.Visible = false;
            }
        }
    }

    private void SetAllRight()
    {
        BtnCustomSearch.Visible = true;
        BtnNew.Visible = true;
        //BtnImport.Visible = true;
        BtnExport.Visible = true;
        detaileditable = true;
        mschart.Visible = true;
        //BtnPrint.Visible = true;
        DelButton.Visible = true;
    }

    protected void CommPageAlert(string msg)
    {
        this.Page.RegisterStartupScript("", "<script>alert('" + msg + "');</script>");        
    }

    public void ReturnBack()
    {       
        if (tableCode == null || tableCode.Equals(""))
            tableCode = (string)ViewState["tableCode"];
        string url = "CommonPage.aspx?IsReturn=true&table=" + tableCode;
        this.Page.Response.Redirect(url);
    }

    public void updateAllOverline(object sender, EventArgs e)
    {

        try
        {
            DbHelper dh = new DbHelper();
            DbCommand dc = dh.GetStoredProcCommond("UPDATEALLOVERLINE");
            dh.ExecuteScalar(dc);
        }
        catch (Exception ex) {
            CommPageAlert(ex.Message);
            this.Page.RegisterStartupScript("", "<script>history.back(-1);</script>");
        }

        this.Page.RegisterStartupScript("", "<script>alert('更新成功！');history.back(-1);</script>");
    }
}
